'use client'

import { Image as ImageIcon, Upload } from 'lucide-react'
import { useCallback } from 'react'
import { Button } from '@/components/ui/button'

interface UploadZoneProps {
  onFileSelect: (file: File) => void
}

export function UploadZone({ onFileSelect }: UploadZoneProps) {
  const validateAndSelectFile = useCallback(
    (file: File) => {
      // Client-side validation for better UX
      const img = new Image()
      const reader = new FileReader()

      reader.onload = (e) => {
        img.onload = () => {
          if (img.width < 20 || img.height < 20) {
            alert(`图片太小！最小尺寸为 20x20 像素，您的图片是 ${img.width}x${img.height} 像素。`)
            return
          }
          if (img.width > 4096 || img.height > 4096) {
            alert(`图片太大！最大尺寸为 4096x4096 像素，您的图片是 ${img.width}x${img.height} 像素。`)
            return
          }
          onFileSelect(file)
        }
        img.onerror = () => {
          alert('无法读取图片文件。请选择有效的图片。')
        }
        img.src = e.target?.result as string
      }

      reader.readAsDataURL(file)
    },
    [onFileSelect],
  )

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault()
      const file = e.dataTransfer.files[0]
      if (file && file.type.startsWith('image/')) {
        validateAndSelectFile(file)
      }
      else if (file) {
        alert('请选择图片文件（JPG、PNG、GIF 等）')
      }
    },
    [validateAndSelectFile],
  )

  const handleFileInput = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0]
      if (file) {
        validateAndSelectFile(file)
      }
    },
    [validateAndSelectFile],
  )

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
  }

  return (
    <Button size="sm" data-testid="button-choose-file" className="relative">
      <Upload className="w-5 h-5 mr-2" />
      选择文件
      <input
        type="file"
        accept="image/*"
        onChange={handleFileInput}
        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
        data-testid="input-file"
        aria-label="选择图片文件"
      />
    </Button>
  )
}
